package com.heima.article.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;

import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;

@Service
@Transactional
@Slf4j
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 生成静态文件上传到minIO中
     *
     * @param apArticle
     * @param content
     */
    @Async
    @Override
    public void buildArticleToMinIO(ApArticle apArticle, String content){

        if (content != null && StringUtils.isNotBlank(content)) {

            //2.文章内容通过freemarker生成html文件
            Template template = null;
            StringWriter stringWriter = null;
            try {
                template = configuration.getTemplate("article.ftl");
                //构建输出流
                stringWriter = new StringWriter();

                //构建数据模型
                HashMap<String, Object> hashMap = new HashMap<>();

                //TODO 将json字符串转为对象
                JSONArray array = JSON.parseArray(content);
                //content与article.ftl中的一致
                hashMap.put("content", array);

                //第一个参数 数据模型
                //第二个参数  输出流
                template.process(hashMap, stringWriter);

            } catch (Exception e) {
                e.printStackTrace();
            }


            //TODO 将字符输出流转为字节输入流
            byte[] bytes = stringWriter.toString().getBytes();
            InputStream inputStream = new ByteArrayInputStream(bytes);

            //3.把html文件上传到minio中
            String url = fileStorageService.uploadHtmlFile("", apArticle.getId() + "html", inputStream);
            //4.修改ap_article表，保存static_url字段
            ApArticle apArticle1 = new ApArticle();
            apArticle1.setStaticUrl(url);
            apArticle1.setId(apArticle.getId());//注意这个
            apArticleMapper.updateById(apArticle1);


            //发送消息，创建索引
            createArticleESIndex(apArticle,content,url);


        }
    }

    /**
     * 发送消息，创建索引
     * @param apArticle
     * @param content
     * @param url
     */
    private void createArticleESIndex(ApArticle apArticle, String content, String url) {
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle,vo);
        vo.setContent(content);
        vo.setStaticUrl(url);
        String jsonString = JSON.toJSONString(vo);
        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC,jsonString);

    }
}
